package com.plian.system.service.pf.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.pf.BasePerformanceEffectDTO;
import com.plian.system.entity.pf.BasePerformanceEffect;
import com.plian.system.entity.pf.PerformanceEffectDetail;
import com.plian.system.entity.sys.Office;
import com.plian.system.enumeratea.BusinessIndicatorsStatus;
import com.plian.system.mapper.pf.BasePerformanceEffectMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pf.IPerformanceEffectDetailService;
import com.plian.system.service.pf.IPerformanceEffectService;
import com.plian.system.service.sys.office.IOfficeService;
import com.plian.system.vo.pf.BasePerformanceEffectVO;
import com.plian.system.wrapper.pf.BasePerformanceEffectWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * @Author: Take-off
 * @Description: TODO
 * @Date: 2023/1/17 9:49 AM
 * @Version: 1.0
 **/
@Service
@AllArgsConstructor
public class PerformanceEffectServiceImpl extends BaseServiceImpl<BasePerformanceEffectMapper, BasePerformanceEffect> implements IPerformanceEffectService, BaseFlowService {

    private IPerformanceEffectDetailService effectDetailService;

    private BasePerformanceEffectWrapper basePerformanceEffectWrapper;

    private GzwProperties gzwProperties;

    private IOfficeService officeService;

    @Override
    public boolean saveOrUpdate(BasePerformanceEffect basePerformanceEffect) {
        if (!Optional.ofNullable(basePerformanceEffect.getId()).isPresent()) {
            basePerformanceEffect.setFormType(String.valueOf(FormTypeConstant.PF_PERFORMANCE_EFFECT));
            basePerformanceEffect.setVersion(1);
            basePerformanceEffect.setIsLatest(2);
        }
        return super.saveOrUpdate(basePerformanceEffect);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            BasePerformanceEffect basePerformanceEffect = getById(id);
            if (basePerformanceEffect == null) {
                return false;
            }
        }
        boolean result = super.deleteLogic(ids);
        if (result){
            effectDetailService.deleteByParentId(ids);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean submit(BasePerformanceEffect basePerformanceEffect) {
        boolean result = saveOrUpdate(basePerformanceEffect);
        if (result){
            List<PerformanceEffectDetail> performanceEffectDetails = basePerformanceEffect.getPerformanceEffectDetails();
            if (CollectionUtil.isNotEmpty(performanceEffectDetails)){
                for (PerformanceEffectDetail effectDetail : performanceEffectDetails){
                    if (effectDetail.getId() != null &&
                            Optional.ofNullable(effectDetail.getIsDeleted()).isPresent() && effectDetail.getIsDeleted().intValue() == 1) {
                        effectDetailService.removeById(effectDetail.getId());
                    }else {
                        effectDetail.setBasePerformanceId(basePerformanceEffect.getId());
                        effectDetailService.saveOrUpdate(effectDetail);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public String checkYear(BasePerformanceEffect basePerformanceEffect) {
        QueryWrapper<BasePerformanceEffect> queryWrapper = new QueryWrapper<>();
        if (!Optional.ofNullable(basePerformanceEffect.getFillingYear()).isPresent()) {
            return "填报时间为空";
        }
        if (!Optional.ofNullable(basePerformanceEffect.getReportOffice()).isPresent()){
            return "填报单位为空";
        }
        queryWrapper.eq("report_office",basePerformanceEffect.getReportOffice());
        queryWrapper.eq("filling_year", basePerformanceEffect.getFillingYear());
        queryWrapper.eq("form_type", FormTypeConstant.PF_PERFORMANCE_EFFECT);
        List<BasePerformanceEffect> list = list(queryWrapper);

        if (CollectionUtil.isEmpty(list)){
            return null;
        }
        return "该年度已填报";
    }

    @Override
    public BasePerformanceEffectVO getDetailObj(BasePerformanceEffect basePerformanceEffect) {
        BasePerformanceEffectVO basePerformanceEffectVO = new BasePerformanceEffectVO();

        Long id = basePerformanceEffect.getId();
        if (Optional.ofNullable(id).isPresent()) {
            basePerformanceEffectVO = basePerformanceEffectWrapper.entityToVO(getById(id));
        }
        //考评内容
        List<PerformanceEffectDetail> detailList = effectDetailService.list(new LambdaQueryWrapper<PerformanceEffectDetail>().eq(PerformanceEffectDetail::getBasePerformanceId, id));
        basePerformanceEffectVO.setPerformanceEffectDetails(detailList);

        return basePerformanceEffectVO;
    }

    @Override
    public ListResult<BasePerformanceEffectVO> list(Query query){
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
        }
        QueryWrapper<BasePerformanceEffect> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new BasePerformanceEffect()), entityList
        );
        //根据登陆权限
        String officeId = TokenUtil.getOfficeId();
        if (Optional.ofNullable(officeId).isPresent() && !officeId.equals(gzwProperties.getAssessmentId())){
            queryWrapper.eq("report_office",officeId);
        }else {
            queryWrapper.eq("status",3);
            queryWrapper.or().eq("report_office",officeId);
        }

        IPage<BasePerformanceEffect> pages = page(Condition.getPage(query), queryWrapper);
        List<BasePerformanceEffectVO> basePerformanceEffectVOS = basePerformanceEffectWrapper.entityToVO(pages.getRecords());

        ListResult<BasePerformanceEffectVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(basePerformanceEffectVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        BasePerformanceEffect effect = getById(id);
        effect.setApprovedUser(TokenUtil.getTokenUserId());
        Date now = DateUtil.now();
        effect.setApprovedTime(now);
        effect.setIsLatest(2);
        effect.setVersion(1);
        effect.setInitialId(Long.valueOf(id));
        effect.setIndicatorStatus(BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
        updateById(effect);

        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<BasePerformanceEffect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BasePerformanceEffect::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<BasePerformanceEffect> performanceEffects = list(queryWrapper);
        List<BasePerformanceEffectVO> performanceEffectVOS = basePerformanceEffectWrapper.entityToVO(performanceEffects);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(performanceEffectVOS)){
                for (BasePerformanceEffectVO vo : performanceEffectVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getReportOfficeName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getReportOffice());
                    pd.put("formType", FormTypeConstant.PF_PERFORMANCE_EFFECT);
                    pd.put("orgName", vo.getReportOfficeName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.PF_PERFORMANCE_EFFECT);
    }

    @Override
    public void goBackToStash(String formId) {
        Long id = Long.valueOf(formId);
        List<BasePerformanceEffect> performanceEffects = list(new LambdaQueryWrapper<BasePerformanceEffect>().eq(BasePerformanceEffect::getInitialId, id));
        if (CollectionUtil.isNotEmpty(performanceEffects) && performanceEffects.size() > 1){
            throw new MyRuntimeException(new ObjResult("该单据已进行其他操作，无法退回！"));
        }
        BasePerformanceEffect performanceEffect = getById(id);
        if (performanceEffect.getStatus() == FormStatusConstant.FINISH){
            LambdaUpdateWrapper<BasePerformanceEffect> updateWrapper = new LambdaUpdateWrapper<>();
            update(updateWrapper.eq(BasePerformanceEffect::getId, id)
                    .set(BasePerformanceEffect::getApprovedUser, null).set(BasePerformanceEffect::getApprovedTime, null)
                    .set(BasePerformanceEffect::getIndicatorStatus, null));
        }

        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    @Override
    public List<PerformanceEffectDetail> getEffectDetails(BasePerformanceEffectDTO dto){
        List<PerformanceEffectDetail> effectDetails= new ArrayList<>();
        if (CollectionUtil.isNotEmpty(dto.getReportOfficeIds())){
            //查询主表
            List<BasePerformanceEffect> baseLists = list(new LambdaQueryWrapper<BasePerformanceEffect>()
                    .in(BasePerformanceEffect::getReportOffice, dto.getReportOfficeIds()).eq(BasePerformanceEffect::getIsLatest,2)
                    .eq(Optional.ofNullable(dto.getYear()).isPresent(),BasePerformanceEffect::getFillingYear,dto.getYear())
                    .eq(BasePerformanceEffect::getStatus,3));
            if (CollectionUtil.isNotEmpty(baseLists)){
                //查询处室
                List<Office> offices = officeService.list(new LambdaQueryWrapper<Office>().in(Office::getId, baseLists.stream().map(BasePerformanceEffect::getReportOffice).collect(Collectors.toList())));
                //主表Id - 处室名字
                Map<Long, String> names = new HashMap<>();
                Map<Long, Long> ids = new HashMap<>();
                baseLists.forEach(base -> {
                    List<Office> officeList = offices.stream().filter(m -> base.getReportOffice().equals(m.getId())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(officeList)){
                        Office office = officeList.get(0);
                        names.put(base.getId(),office.getName());
                        ids.put(base.getId(),office.getId());
                    }
                });

                List<PerformanceEffectDetail> effectDetailList = effectDetailService.list(new LambdaQueryWrapper<PerformanceEffectDetail>().in(PerformanceEffectDetail::getBasePerformanceId, baseLists.stream().map(BasePerformanceEffect::getId).collect(Collectors.toList())));
                if (CollectionUtil.isNotEmpty(effectDetailList)){
                    String keyword = dto.getKeyword();
                    if (Optional.ofNullable(keyword).isPresent()){
                        //关键词筛选
                        effectDetails = effectDetailList.stream().filter(m -> m.getCheckItem().contains(keyword) || m.getScoreMethod().contains(keyword)).collect(Collectors.toList());
                    }else {
                        effectDetails = effectDetailList;
                    }
                    //set 处室名字
                    if (CollectionUtil.isNotEmpty(effectDetails)){
                        effectDetails.forEach(detail ->{
                            String officeName = names.get(detail.getBasePerformanceId());
                            Long officeId = ids.get(detail.getBasePerformanceId());
                            detail.setReportOfficeName(officeName);
                            detail.setReportOffice(officeId);
                        });
                    }
                }
            }
        }
        return effectDetails;
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id          主键
     * @param updateStatus  更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            BasePerformanceEffect tripleMeeting = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH){
                tripleMeeting.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                tripleMeeting.setApprovedTime(now);
            }
            tripleMeeting.setStatus(updateStatus);
            updateById(tripleMeeting);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }


}
